package com.psp.web.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.northend.util.StringUtil;
import com.psp.web.cache.dao.ServiceCategoryCacheDao;
import com.psp.web.controller.res.bean.RAttributeBean;
import com.psp.web.controller.res.bean.RAttributeValueBean;
import com.psp.web.controller.res.bean.RBusinessCommentsBean;
import com.psp.web.controller.res.bean.RBusinessDetailBean;
import com.psp.web.controller.res.bean.RProductListBean;
import com.psp.web.controller.res.bean.RProductSkuBean;
import com.psp.web.controller.res.bean.RServicesMenusBean;
import com.psp.web.controller.res.bean.RServicesTypeBean;
import com.psp.web.controller.res.bean.RSimilarProductBean;
import com.psp.web.model.CommentBean;
import com.psp.web.model.ProductAttributeBean;
import com.psp.web.model.ProductBean;
import com.psp.web.model.ProductSkuBean;
import com.psp.web.model.ServiceCategoryBean;
import com.psp.web.model.ServiceMenuTree;
import com.psp.web.model.vo.ServiceCategoryLevelVO;
import com.psp.web.persist.dao.CommentDao;
import com.psp.web.persist.dao.ProductDao;
import com.psp.web.persist.dao.ServiceCategoryDao;
import com.psp.web.service.ProductService;
import com.psp.web.service.exception.ServiceException;

@Service
public class ProductServiceImpl implements ProductService {

	@Autowired
	ProductDao productImpl;

	@Autowired
	CommentDao commentImpl;

	@Autowired
	ServiceCategoryDao serviceCategoryImpl;

	@Autowired
	ServiceCategoryCacheDao serviceCategoryCacheImpl;

	@Override
	public RServicesTypeBean getServiceTypes() {
		RServicesTypeBean bean = new RServicesTypeBean();

		JSONArray jsonArray = new JSONArray();

		String jsonStr = serviceCategoryCacheImpl.getServiceCatesJsonStr();
		JSONObject firstObject = new JSONObject();
		firstObject.put("name", "全部");
		firstObject.put("code", 0);
		JSONArray subArr = new JSONArray();
		JSONObject sub = new JSONObject();
		sub.put("name", "全部");
		sub.put("code", 0);
		subArr.add(sub);
		firstObject.put("subServices", subArr);
		jsonArray.add(firstObject);
		if (StringUtil.isEmpty(jsonStr)) {
			List<ServiceCategoryBean> MenuCates = serviceCategoryImpl.selectAllTypes2Menu();
			if(MenuCates == null) {
				return null;
			}
			for (ServiceCategoryBean cate : MenuCates) {
				JSONObject faObject = new JSONObject();
				JSONArray secondService = new JSONArray();
				JSONObject secondSub = new JSONObject();
				secondSub.put("name", "全部");
				secondSub.put("code", 0);
				secondService.add(secondSub);
				faObject.put("name", cate.getName());
				faObject.put("code", cate.getCode());
				List<ServiceCategoryBean> children = cate.getChildern();
				if(children != null && children.size() > 0) {
					for(ServiceCategoryBean ss : children) {
						JSONObject secondObj = new JSONObject();
						secondObj.put("name", ss.getName());
						secondObj.put("code", ss.getCode());
						secondService.add(secondObj);
					}
					faObject.put("subServices", secondService);
					jsonArray.add(faObject);
				}
			}
			serviceCategoryCacheImpl.setServiceCategory(jsonArray.toJSONString());
		} else {
			jsonArray = JSON.parseArray(jsonStr);
		}
		bean.setServiceType(jsonArray);

		return bean;
	}

	@Override
	public RServicesMenusBean getServiceMenus() {
		RServicesMenusBean bean = new RServicesMenusBean();
		JSONArray jsonArray = new JSONArray();
		String jsonStr = serviceCategoryCacheImpl.getCategoryJsonStr();
		if (StringUtil.isEmpty(jsonStr)) {
			List<ServiceCategoryBean> MenuCates = serviceCategoryImpl.selectAllTypes2Menu();
			if(MenuCates == null) {
				return null;
			}
			for(ServiceCategoryBean sc : MenuCates) {
				JSONObject firstObject = new JSONObject();
				firstObject.put("name", sc.getName());
				firstObject.put("code", sc.getCode());
				List<ServiceCategoryBean> children = sc.getChildern();
				List<ServiceMenuTree> sub = null;
				if(children != null && children.size() > 0) {
					sub = new ArrayList<ServiceMenuTree>();
					for(ServiceCategoryBean c : children){
						List<ProductBean> ps = productImpl.selectListByCateCode(new HashSet<Integer>() {{add(c.getCode());}});
						ServiceMenuTree menus = new ServiceMenuTree(c.getName(), c.getCode(), ps);
						sub.add(menus);
					}
				}
				firstObject.put("children", sub);
				jsonArray.add(firstObject);
			}
			String jsonMenu = JSON.toJSONString(jsonArray);
			serviceCategoryCacheImpl.setCategoryMenu(jsonMenu);
		} else {
			jsonArray = JSON.parseArray(jsonStr);
		}
		bean.setServiceMenus(jsonArray);
		return bean;
	}

	@Override

	public PageResult<RProductListBean> getLists(Integer page, Integer pageSize, Integer firstType, Integer secType) {
		PageResult<RProductListBean> result = new PageResult<>();
		List<RProductListBean> lists = new ArrayList<>();
		List<ProductBean> resList = new ArrayList<>();
		int count = 0;
		if (firstType == 0) {// 查找全部
			count = productImpl.selectAllCount();
			resList = productImpl.selectAllList(page, pageSize);
		} else {

			count = productImpl.selectCount(firstType, secType);
			resList = productImpl.selectList(page, pageSize, firstType, secType);
		}
		if (resList != null) {
			for (ProductBean bean : resList) {
				RProductListBean rb = new RProductListBean();
				rb.setPcode(bean.getPcode());
				rb.setPid(bean.getPid());
				rb.setTitle(bean.getTitle());
				rb.setSubTitle(bean.getSubTitle());
				rb.setType(bean.getType());
				rb.setImg(bean.getImg());
				rb.setPrice(bean.getPrice());
				rb.setQuoteType(bean.getQuoteType());
				rb.setSatisfaction(bean.getSatisfaction());
				rb.setSellNum(0); // TODO 商品交易量
				lists.add(rb);
			}
		}

		result.setData(lists);
		result.setCount(count);
		return result;
	}

	@Override
	public RBusinessDetailBean getDetail(String pid) {
		ProductBean bs = productImpl.selectById(pid);
		if (bs == null) {
			throw new ServiceException("object_is_not_exist", "服务");
		}
		
		RBusinessDetailBean rb = new RBusinessDetailBean();
		rb.setPcode(bs.getPcode());
		rb.setPid(bs.getPid());
		rb.setTitle(bs.getTitle());
		rb.setSubTitle(bs.getSubTitle());
		rb.setType(bs.getType());
		rb.setImg(bs.getImg());
		rb.setServiceContent(bs.getServiceContent());
		rb.setServiceSafe(bs.getServiceContent());
		rb.setPrice(bs.getPrice());
		rb.setQuoteType(bs.getQuoteType());
		rb.setLinkMan(bs.getLinkMan());
		rb.setTelephone(bs.getTelephone());
		rb.setHasInvoice(bs.getHasInvoice() == 1 ? true : false);
		rb.setSatisfaction(bs.getSatisfaction());
		rb.setFirstCode(bs.getFirstCode()+"");
		rb.setFirstCate(bs.getFirstCate());
		rb.setSecondCate(bs.getSecondCate());
		// 获得评论
		int bsCount = commentImpl.selectBsCount(pid);
		rb.setCommentNum(bsCount);

		return rb;
	}

	@Override
	public PageResult<RBusinessCommentsBean> getComments(int page, int pageSize, String bid) {
		PageResult<RBusinessCommentsBean> result = new PageResult<RBusinessCommentsBean>();

		int count = commentImpl.selectBsCount(bid);
		List<CommentBean> reslist = commentImpl.selectBsList(page, pageSize, bid);
		List<RBusinessCommentsBean> dataLists = new ArrayList<>();

		if (reslist != null && reslist.size() > 0) {
			for (CommentBean bean : reslist) {
				RBusinessCommentsBean rb = new RBusinessCommentsBean();
				rb.setCid(bean.getCid());
				rb.setCreate(bean.getCreateDate().getTime());
				rb.setScore(bean.getScore());
				rb.setContent(bean.getContent());
				rb.setReplyContent(bean.getReplyContent());
				rb.setReplyDate(bean.getReplyDate() == null ? null : bean.getReplyDate().getTime());

				rb.setNickName(bean.getuNickName());
				rb.setBSpeed(bean.getoSpeed() == 1 ? "普通" : bean.getoSpeed() == 2 ? "加急" : "");
				rb.setBTitle(bean.getbTitle());

				dataLists.add(rb);
			}

		}
		result.setCount(count);
		result.setData(dataLists);

		return result;
	}

	@Override
	public RSimilarProductBean getSimilarBs(String pid) {
		RSimilarProductBean bean = new RSimilarProductBean();
		ProductBean bs = productImpl.selectById(pid);

		JSONArray resultArray = new JSONArray();
		if (bs != null) {
			Integer cateCode = bs.getTypeCode();
			// ServiceCategoryBean cate = serviceCategoryImpl.selectByCode(cateCode);
			List<ServiceCategoryLevelVO> list = serviceCategoryImpl.selectLevel1AllByCode(cateCode);
			List<ProductBean> productList = null;
			Map<Integer, String> serviceCateMap = new HashMap<>();
			Set<Integer> serviceCateSet = null;
			if (list != null && list.size() > 0) {
				serviceCateSet = new HashSet<>();
				for (ServiceCategoryLevelVO rbVo : list) {
					serviceCateMap.put(rbVo.getCode3(), rbVo.getName3());
					serviceCateSet.add(rbVo.getCode3());
				}
				if (serviceCateSet.size() > 0) {
					productList = productImpl.selectListByCateCode(serviceCateSet);
				}
			}
			Map<Integer, List<JSONObject>> resData = new HashMap<>();
			if (productList != null && productList.size() > 0) {
				for (ProductBean rb : productList) {
					Integer typeCode = rb.getTypeCode();
					List<JSONObject> pids = resData.get(typeCode);
					if (pids == null) {
						pids = new ArrayList<>();
					}
					JSONObject pido = new JSONObject();
					pido.put("pid", rb.getPid());
					pido.put("title", rb.getTitle());
					pids.add(pido);
					resData.put(typeCode, pids);
				}
			}

			if (resData != null && resData.size() > 0) {
				for (Integer key : resData.keySet()) {
					List<JSONObject> value = resData.get(key);
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("title", serviceCateMap.get(key));
					jsonObject.put("sub", value);
					resultArray.add(jsonObject);
				}
			}
		}
		bean.setSimilarProduct(resultArray);
		return bean;
	}

	@Override
	public List<RAttributeBean> getAttributes(String pid) {
		List<RAttributeBean> result = new ArrayList<>();
		List<ProductAttributeBean> attributes = productImpl.selectAttributeList(pid);
		if (attributes.size() > 0) {
			for (ProductAttributeBean a : attributes) {
				RAttributeBean ra = new RAttributeBean();
				ra.setAcode(a.getAcode());
				ra.setAid(a.getAid());
				ra.setName(a.getName());
				List<RAttributeValueBean> values = JSONArray.parseArray(a.getValue(), RAttributeValueBean.class);
				int i = 0;
				for (RAttributeValueBean v : values) {
					v.setSelected(i++ == 0 ? 1 : 0);
				}
				ra.setValue(values);
				result.add(ra);
			}
		}
		return result;
	}

	@Override
	public RProductSkuBean getProductInfoBySkuno(String skuCode) {
		RProductSkuBean res = null;

		ProductSkuBean skuBean = productImpl.selectProductInfoBySukCode(skuCode);
		if (skuBean != null) {
			res = new RProductSkuBean();
			res.setNum(skuBean.getNum());
			res.setPrice(skuBean.getPrice());
			res.setSkuId(skuBean.getSkuId());
			res.setSkuJson(skuBean.getSkuJson());
			res.setPid(skuBean.getPid());
		}
		return res;
	}

}
